package org.linlinjava.litemall.db.service;

import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.BenefitMapper;
import org.linlinjava.litemall.db.dao.LitemallBenefitMapper;
import org.linlinjava.litemall.db.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class LitemallBenefitService {

    @Resource
    private LitemallBenefitMapper litemallBenefitMapper;

    @Resource
    private BenefitMapper benefitMapper;

    public List<LitemallBenefit> query(Integer userId, Integer page, Integer limit, String sort, String order, String type) {
        LitemallBenefitExample example = new LitemallBenefitExample();
        LitemallBenefitExample.Criteria criteria = example.or().andSourceIdEqualTo(userId);// todo delete判断加到xml中了，因为管理表无法判断是那个delete
        if (!StringUtils.isEmpty(type)) {
            criteria.andEventEqualTo(Short.valueOf(type));
        }
        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }
        PageHelper.startPage(page, limit);
        return litemallBenefitMapper.selectByExampleSelective(example);
    }

    public BigDecimal sumBenefit(Integer userId) {
        return benefitMapper.sumBenefit(userId);
    }

    public void add(LitemallBenefit record) {
        record.setAddTime(LocalDateTime.now());
        record.setUpdateTime(LocalDateTime.now());
        litemallBenefitMapper.insertSelective(record);
    }

    /**
     * 查询是否已存在相同事件记录
     * @param sourceId
     * @param followerId
     * @param event
     * @return
     */
    public boolean checkExist(Integer sourceId, Integer followerId, Short event) {
        LitemallBenefitExample example = new LitemallBenefitExample();
        example.or().andSourceIdEqualTo(sourceId).andFollowerIdEqualTo(followerId).andEventEqualTo(event).andDeletedEqualTo(false);
        return litemallBenefitMapper.countByExample(example) != 0;
    }
}
